package com.example.yuan0605.test;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class Users extends SQLiteOpenHelper {
    Context context;
    private static final String DB_NAME = "users.db"; // 数据库名称
    public Users(Context context, int version) {
        super(context, DB_NAME, null, version);
        this.context=context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql="create table user (userId integer primary key autoincrement ,username varchar(10) not null,password varchar(10) not null)";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //备份到文件里面
        List<User> beifen = SQLOpenHelperActivity.beifen(db);
        try {
            FileOutputStream fileOutputStream = context.openFileOutput("users.txt", Context.MODE_PRIVATE);
            String sj=beifen.toString();
            fileOutputStream.write(sj.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //添加sex字段
        db.execSQL("alter table user add sex varchar(5)");
    }
}
